<?php

namespace Frieza\Modules\Guide\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\GuideCounter;
use Doraemon\model\PhotoJoinGuide;
use Doraemon\model\PublishGuide as mPublishGuide;
use Doraemon\pockets\excel\DownExcel;
use Doraemon\service\Guide as sGuide;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\IdParse;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;


class PublishGuideController extends Controller
{
    public function index(Request $request, Content $content)
    {
        $tab = new tab();
        $title = '指南发布列表';
        $tab->add($title, $this->listData($request));

        return $content
            ->header('指南文章管理')
            ->breadcrumb(
                ['text' => $title]
            )
            ->body($tab);
    }

    public function del($id = '')
    {
        $status = false;
        $message = "操作失败，删除失败";

        try {
            $data["status"] = mPublishGuide::STATUS_DELETE;
            $data['edittime'] = time();
            $where['id'] = $id;
            if (mPublishGuide::update($data, $where)) {
                //删除指南solr数据
                \Doraemon\cache\Queue::insertQueue('Guide/deleteSearch', [
                    'guide_id' => $id, //当前操作者uid
                ]);
                \Doraemon\cache\Queue::insertQueue('TotalArticle/delArticleById', [
                    'article_id' => $id, //当前操作者uid
                ]);
                \Doraemon\cache\Queue::insertQueue('Dynamic/delGuideDynamic', [
                    'obj_id' => $id, //当前操作者uid
                ]);
                $relation_data = PhotoJoinGuide::select(['guide_id' => $id]);

                if ($relation_data && is_array($relation_data)) {
                    foreach ($relation_data as $current_relation) {
                        //删除图片信息缓存
                        \Doraemon\cache\Queue::insertQueue('Photo/delCacheById', [
                            'photo_id' => $current_relation['photo_id'], //当前操作者uid
                        ]);
                    }
                    //删除图片关系
                    PhotoJoinGuide::delete(['guide_id' => $id]);
                }

                //解除wiki关联
                $uid = IdParse::getUid($id);
                \Biz\service\wiki\ObjRelateWiki::delGuideRelate($uid, $id);

                $status = true;
                $message = "操作成功";
            }
        } catch (\Exception $e) {
            $status = false;
            $message = "操作失败,信息:" . $e->getMessage();
        } finally {
            return response()->json(compact('status', 'message'));
        }
    }

    private function listData(Request $request)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 10);
        $search = $request->input('search', []);

        $query["AND"]['type'] = 0;
        $query["AND"]['status'] = mPublishGuide::STATUS_NORMAL;
        if (isset($search['uid']) && is_numeric($search['uid'])) {
            $query["AND"]['uid'] = $search['uid'];
        }

        if (!empty($search['keyword'])) {
            $query["OR"]['title[~]'] = "%" . $search['keyword'] . "%";;
            $query["OR"]['admin_tag[~]'] = "%" . $search['keyword'] . "%";;
        }

        $guide = $this->getGuideData($query, $page, $pageSize);

        foreach ($guide['data'] as  &$val) {
            $val['guide_id'] = $val['id'];
            $counter = GuideCounter::getOne($val['id'], true);
            $val['read_total'] = $counter['read']-$counter['read_rnd']-$counter['read_share'];
            $val['favorite'] = $counter['favorite'];
            $val['share'] = $counter['share'];
            $val['comment'] = $counter['comment'];
        }

        $gridModel = new pGridDataModel($guide['data'], $guide['total'], ['perPage' => $pageSize, '']);

        $gridModel->setKeyType('string');
        $gridModel->setKeyName("guide_id");

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $search) {
            $grid->disableExport();
            $grid->disableCreateButton();
            $grid->disableRowSelector();
            $grid->paginate($gridModel->getPerPage());
            $grid->tools(function ($tools) {
                $tools->append(<<<HTML
<a class="btn button-success" href="/admin/guide/publish/export">
    <i class="fa fa-download"/> 居住指南下载
</a>
HTML
                );
            });

            //筛选
            $grid->filter(function (Grid\Filter $filter) use ($search) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($search) {
                    $filter->equal('search.uid', '发布账号')->select(sGuide::AUTHERS)->default($search['uid']);
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($search) {
                    $filter->equal('search.keyword', '关键字')->default($search['keyword']);
                });

                //条件展开
                if ($search) $filter->expand();
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
            });

            $grid->column('guide_id', "专题Id");
            $grid->column('type', "专题类型")->display(function(){
                return "指南";
            });
            $grid->column('number', "期数")->display(function ($number) {
                return "第{$number}期";
            });
            $grid->column('uid', "作者")->using(sGuide::AUTHERS);
            $grid->column('title', "标题");
            $grid->column('admin_tag', "标签");
            $grid->column('read_total', "总阅读")->sortable();
            $grid->column('favorite', "收藏")->sortable();
            $grid->column('share', "分享")->sortable();
            $grid->column('show', "分享页")->display(function () {
                $url = Hhzurl::h5ZhinanShow($this->guide_id);
                return "<a href=" .$url. " target='_blank' >"."分享页"."</a>";
            });
            $grid->column('comment', "评论")->sortable();
            $grid->column('addtime', "发布时间")->display(function ($addtime) {
                return date("Y-m-d H:i:s", $addtime);
            });
            $grid->column('status', "状态")->display(function () {
                return "正常";
            });;
            $grid->disableRowSelector(false);

            $grid->actions(function ($actions) {
                $actions->disableView();
                $actions->disableEdit();


            });
        });

        return $listGrid->render();

    }

    private function getGuideData($query, $page, $pageSize)
    {
        $guide = [
            "total" => 0,
            "data" => []
        ];

        $query["ORDER"] = [
            'number' => "DESC",
            'addtime' => "DESC"
        ];

        $query["LIMIT"] = [ ($page - 1) * $pageSize, $pageSize];

        $list = mPublishGuide::select("*" , $query);

        unset($query["LIMIT"]);
        unset($query["ORDER"]);
        $count = mPublishGuide::count($query);

        if ($list && is_array($list)){
            $guide = [
                "total" => $count,
                "data" => $list
            ];
        }
        return $guide;
    }

    public function export(Request $request, Content $content)
    {
        Admin::script($this->DownScript());
        $query = $request->all();
        $start_time = strtotime($query["start_time"]);
        $end_time = strtotime($query["end_time"]);
        if (empty($start_time) || empty($end_time)) {
            $form = new Form();

            $form->datetime('start_time', '开始时间');
            $form->datetime('end_time', '结束时间');
            $form->html("<a href='javascript:;' class='btn btn-default export'>下载</a>");
//            $form->action('/admin/guide/publish/export');
            $form->disableReset();
            $form->disableSubmit();
            return $content
                ->row($form->render());
        } else {
            $where = [
                'type' => mPublishGuide::TYPE_GUIDE,
                'addtime[>=]' => $start_time,
                'addtime[<=]' => $end_time,
                'status' => mPublishGuide::STATUS_NORMAL
            ];

            $exportData = mPublishGuide::select('*', $where);

            if (empty($exportData)) {
                $result = ['status' => 1, 'message' => '暂无数据可以导出'];
                return response()->json($result);
            }

            $downExcel = new DownExcel();
            $title = date("YmdHis");
            $downExcel->setFrontBold('1');
            $downExcel->setFileName($title);
            $downExcel->setTitle($title);
            $downExcel->setSheetTitle($title);
            $widths = [
                'A' => 30,
                'B' => 20,
                'C' => 30,
                'D' => 50,
                'E' => 10,
                'F' => 10,
                'G' => 10,
                'H' => 10,
                'I' => 30,
            ];
            $downExcel->setWidth($widths);
            $head = [
                '专题id',
                '期数',
                '标题',
                '标签',
                '阅读',
                '收藏',
                '分享',
                '评论',
                '发布时间',
            ];
            foreach ($exportData as $row) {
                $counter = GuideCounter::getOne($row['id']);
                $data[] = [
                    $row['id'],
                    $row['number'],
                    $row['title'],
                    $row['admin_tag'],
                    $counter['read'],
                    $counter['favorite'],
                    $counter['share'],
                    $counter['comment'],
                    date('Y-m-d H:i:s', $row['addtime']),
                ];
            }
            if (!empty($data)) {
                $downExcel->create($data, $head);
            }
            return back();
        }
    }

    public function DownScript()
    {
        return <<<SCRIPT
            $('.export').click(function() {
                var start = $('#start_time').val();
                var end =$('#end_time').val();
                window.location.href = "/admin/guide/publish/export?start_time="+start+"&end_time="+end
            });
            SCRIPT;
    }
}